# 自定义用户认证的后端：实现多账号登录
from django.contrib.auth.backends import ModelBackend
import re
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from django.conf import settings
from itsdangerous import BadData
from users.models import User
from . import constants


def check_verify_email_token(token):
    """
    验证token并提取user
    :param token: 用户信息签名后的结果
    :return: user, None
    """
    serializer = Serializer(settings.SECRET_KEY, expires_in=constants.VERIFY_EMAIL_TOKEN_EXPIRES)
    try:
        data = serializer.loads(token)
    except BadData:
        return None
    else:
        user_id = data.get('user_id')
        email = data.get('email')
        try:
            user = User.objects.get(id=user_id, email=email)
        except User.DoesNotExist:
            return None
        else:
            return user

def generate_verify_email_url(user):
    """
    生成商城邮箱激活链接

    """
    s = Serializer(settings.SECRET_KEY, constants.VERIFY_EMAIL_TOKEN_EXPIRES)
    data = {'user_id':user.id,'email':user.email}
    token = s.dumps(data)
    return settings.EMAIL_VERIFY_URL + '?token=' + token.decode()


def get_user_by_account(account):
    """
    通过账号获取用户
    :param account:
    :return:
    """
    try:
        if re.match(r'^1[3-9]\d{9}$', account):
            # username = '手机号码'
            user = User.objects.get(mobile=account)
        else:
            # username = ‘用户名’
            user = User.objects.get(username=account)
    except User.DoesNotExist:
        return None
    else:
        return user

class UserMobileBackend(ModelBackend):
    """自定义用户认证后端"""

    def authenticate(self, request, username=None, password=None, **kwargs):
        """重写用户认证的方法
        """
        # 校验username是用户名还是手机号
        # try:
        #     if re.match(r'^1[3-9]\d{9}$', username):
        #         # username = '手机号码'
        #         user =User.objects.get(mobile = username)
        #     else:
        #         # username = ‘用户名’
        #         user =User.objects.get(username = username)
        # except User.DoesNotExist:
        #     return None
        # else:
        #     return user
        # 使用账号查询用户
        if request is None:
            # 后台登录
            try:
                user = User.objects.get(username=username, is_superuser=True)
            except:
                user = None
            if user is not None and user.check_password(password):
                return user

        else:
            user = get_user_by_account(username)
            # 如果可以查询到用户，还需要校验密码是否校验密码是否正确
            if user and user.check_password(password):
                # 返回user
                return user
            else:
                return None

